var gameConfig = cc.Class({
    init(){
        this.gameData = {};
        this.headArr = [];
        this.clothingArr = [];

        this.initGameData();

        var self = this;
        cc.loader.loadResDir("image/head/", cc.SpriteFrame,(err, head)=>{
            self.saveHeadOrClothingSprite("headArr", head);
        });

        cc.loader.loadResDir("image/clothing/", cc.SpriteFrame,(err, clothing)=>{
            self.saveHeadOrClothingSprite("clothingArr", clothing);
        });
    },

    initGameData:function(){
        var level = this.getGameData("level");//关卡
        var coin = this.getGameData("coin");//体力
        var hintNumber = this.getGameData("hintNumber");//体力
        var isMusic = this.getGameData("isMusic");//是否开启游戏背景音乐
        var isSound = this.getGameData("isSound");//是否开启游戏音效
        var levelEndData = this.getGameData("levelEndData");//已通过关卡的数据 

        if(!level)level = 1;
        this.saveGameData("level", level);

        if(!hintNumber)hintNumber = 0;
        this.saveGameData("hintNumber", hintNumber);

        if(!coin)coin = 500;
        this.saveGameData("coin", coin);

        if(!isMusic)isMusic = 1;
        this.saveGameData("isMusic", isMusic);
        
        if(!isSound)isSound = 1;
        this.saveGameData("isSound", isSound);

        if(!levelEndData)levelEndData = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0";
        this.saveGameData("levelEndData", levelEndData);
    },

    //保存游戏数据
    saveGameData(key, value){
        this.gameData[key] = value;
        this.setGameConfigData(key, value)
    },
    
    //获取游戏数据
    getGameData(config){
        let data = cc.sys.localStorage.getItem(config);
        return data;
    },

    //设置游戏数据
    setGameConfigData:function(key, value){
        cc.sys.localStorage.setItem(key,value);
    },

    saveHeadOrClothingSprite:function(type, spriteArr){
        if(type == "headArr")window.headArr = spriteArr;
        else window.clothingArr = spriteArr;
    },

    /**
     * 
     * @param {类型 头部或者衣服} type 
     * @param {图片名称} name 
     * @param {回调方法} callback 
     */
    getSpriteHeadOrClothingByType(type,name, callback){
        var findArr;
        if(type == "head")findArr = window.headArr;
        else findArr = window.clothingArr;

        for(let i = 0; i < findArr.length; i++)
        {
            if(findArr[i].name == name)
            {
                callback(findArr[i]);
            }
        }
    }
});

module.exports = gameConfig;